import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Border, Side, PatternFill
import os

new_path = '/新版文件'
border = Border(left=Side(border_style='thin', color='000000'),
                right=Side(border_style='thin', color='000000'),
                top=Side(border_style='thin', color='000000'),
                bottom=Side(border_style='thin', color='000000'))
orange_fill = PatternFill(fill_type='solid', fgColor="FFC125")


def write_data(names, head, row_data, path):
  folder = mkdir(path)
  file_boolean = os.path.exists(path + new_path + '/' + names + '.xlsx')
  if not file_boolean:
    workbook = Workbook()
    # 默认sheet
    sheet = workbook.active
    sheet.title = names
    # 有效列数
    rows, columns = get_row_clo_num(sheet)
    # sheet = workbook.create_sheet(title="新sheet")
    sheet.append(head)

    # 填充颜色
    for x in range(1, len(head) + 1):
      sheet.cell(row=1, column=x).border = border
      sheet.cell(row=1, column=x).fill = orange_fill
    for data in row_data:
      sheet.append(data)

    for j in range(1, rows + 1):
      for k in range(1, columns + 1):
        sheet.cell(row=j, column=k).border = border
    workbook.save(folder + '/' + names + '.xlsx')
  # 如果存在就要修改当前文件
  else:
    data = openpyxl.load_workbook(folder + '/' + names + '.xlsx')
    table = data.active

    for value in row_data:
      table.append(value)
    rows, columns = get_row_clo_num(table)
    for j in range(1, rows + 1):
      for k in range(1, columns + 1):
        table.cell(row=j, column=k).border = border
    data.save(folder + '/' + names + '.xlsx')


# 创建文件夹
def mkdir(path):
  print(path)
  folder = os.path.exists(path + new_path)
  if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
    os.makedirs(path + new_path)
  return path + new_path


# 获取最大行数最大列数
def get_row_clo_num(sheet):
  rows = sheet.max_row
  columns = sheet.max_column
  return rows, columns
